<template>
  <div class="check-in-view">
    <div class="header">
      <h2>学生签到</h2>
    </div>

    <el-card class="calendar-card">
      <el-calendar v-model="calendarDate">
        <template #date-cell="{ data }">
          <div class="date-cell">
            <span>{{ data.day.split('-').slice(2)[0] }}</span>
            <el-tag v-if="isCheckedIn(data.day)" type="success" size="small">已签到</el-tag>
          </div>
        </template>
      </el-calendar>
    </el-card>

    <el-card class="check-in-form">
      <el-form inline>
        <el-form-item label="选择课程">
          <el-select v-model="selectedCourseId" placeholder="请选择课程" clearable>
            <el-option
              v-for="course in joinedCourses"
              :key="course.id"
              :label="course.title"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleCheckIn"
            :disabled="!selectedCourseId"
            :icon="Plus"
          >签到</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="check-in-records">
      <div class="records-header">
        <h3>签到记录</h3>
      </div>
      <el-table :data="checkInStore.checkIns" style="width: 100%">
        <el-table-column prop="id" label="ID" width="200"></el-table-column>
        <el-table-column prop="courseTitle" label="课程"></el-table-column>
        <el-table-column prop="checkInTime" label="签到时间"></el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { useCheckInStore, CheckInDto } from '@/stores/api/check-in';
import { useCourseStore } from '@/stores/api/course';
import { useCourseJoinStore } from '@/stores/api/course-join';
import { useUserStore } from '@/stores/api/user';

const checkInStore = useCheckInStore();
const courseStore = useCourseStore();
const courseJoinStore = useCourseJoinStore();
const userStore = useUserStore();

const calendarDate = ref(new Date());
const selectedCourseId = ref<number | null>(null);
const joinedCourses = ref<any[]>([]);
const checkInRecords = ref<CheckInDto[]>([]);

const isCheckedIn = (date: string) => {
  return checkInRecords.value.some(record => record.checkInTime.startsWith(date));
};

const fetchJoinedCourses = async () => {
  if (!userStore.user?.id) {
    ElMessage.error('请先登录');
    return;
  }
  try {
    await courseStore.fetchCourses();
    const joins = await courseJoinStore.fetchJoinRequestsByStudent(userStore.user.id);
    const approvedJoins = joins.filter((join: any) => join.status === 'APPROVED');
    const courseIds = approvedJoins.map((join: any) => join.courseId);
    joinedCourses.value = courseStore.courses.filter(course => courseIds.includes(course.id));
  } catch (error) {
    ElMessage.error('获取已加入课程失败');
  }
};

const handleCheckIn = async () => {
  if (!userStore.user?.id) {
    ElMessage.error('请先登录');
    return;
  }
  if (!selectedCourseId.value) {
    ElMessage.error('请选择课程');
    return;
  }
  try {
    await checkInStore.createCheckIn({ courseId: selectedCourseId.value, studentId: userStore.user.id });
    await fetchCheckInRecords();
    ElMessage.success('签到成功');
  } catch (error) {
    ElMessage.error('签到失败');
  }
};

const fetchCheckInRecords = async () => {
  if (!userStore.user?.id) return;
  try {
    checkInRecords.value = await checkInStore.fetchCheckInsByStudent(userStore.user.id);
  } catch (error) {
    ElMessage.error('获取签到记录失败');
  }
};

onMounted(() => {
  fetchJoinedCourses();
  fetchCheckInRecords();
});
</script>

<style scoped>
.check-in-view {
  width: 80%;
  margin: 40px auto 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  font-size: 24px;
  color: #333;
  flex-grow: 1;
  text-align: center;
}

.check-in-form .el-select {
  width: 200px;
}

.calendar-card,
.check-in-form,
.check-in-records {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.date-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.date-cell .el-tag {
  margin-top: 5px;
}

.records-header h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 10px;
}

.el-table {
  border-radius: 8px;
}
</style>